﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using System.Threading;
//using System.Web;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Phone.Net.NetworkInformation;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Events;
using WeiboPlus.Models;
using WeiboPlus.Service;
using WeiboPlus.Service.Event;
using WeiboPlus.Shell.ViewModel;
//using WeiboPlus.Sina;
using WeiboPlus.Common;
using GalaSoft.MvvmLight.Messaging;
using WeiboPlus.Shell.Events;
using WeiboPlus.ViewModel;

namespace WeiboPlus.Shell.ViewModel
{
    public class MainViewModel : CollectionVMBase<SNSStatusViewModel>
    {
        #region Field
        SNSCounts _counts;
        object _countsObj = new object();
        SNSPagingInfo _pagingInfo;
        int pagecount = 10;
        int _page = 0;
        ISNSPollingService _pollingSvc;
        IStatusService _statusSvc;
        private IEventAggregator _ev;
        #endregion

        #region Property
        string userName;

        public string UserName
        {
            get { return userName; }
            set { userName = value; RaisePropertyChanged("UserName"); }
        }

        public ApplicationSetting AppSetting
        {
            get { return PhoneApplicationController.Current.AppSetting; }
        }

        private string countInfoText;

        public string CountInfoText
        {
            get
            {
                return countInfoText;
            }
            set
            {
                if (value == countInfoText)
                    return;
                countInfoText = value;
                RaisePropertyChanged("CountInfoText");
            }
        }

        private ObservableCollection<SNSAccount> bindedAccounts;

        public ObservableCollection<SNSAccount> BindedAccounts
        {
            get { return bindedAccounts; }
            set
            {
                bindedAccounts = value;
                RaisePropertyChanged(() => BindedAccounts);
            }
        }

        string statusToUpdate;

        public string StatusToUpdate
        {
            get { return statusToUpdate; }
            set
            {
                statusToUpdate = value;
                RaisePropertyChanged(() => StatusToUpdate);
            }
        }

        BitmapImage imageToSend;

        public BitmapImage ImageToSend
        {
            get { return imageToSend; }
            set
            {
                imageToSend = value;
                RaisePropertyChanged(() => ImageToSend);
            }
        }

        public Action<SNSStatusViewModel, string> OnRefreshed { get; set; }
        public Action<SNSStatusViewModel, string> OnNextPagePerformed { get; set; }
        string searchKeyword;

        public string SearchKeyword
        {
            get { return searchKeyword; }
            set
            {
                searchKeyword = value;

                if (PivotSelectedIndex != 4)
                {
                    PivotSelectedIndex = 4;
                }

                RaisePropertyChanged(() => SearchKeyword);
            }
        }

        int pivotSelectedIndex;

        public int PivotSelectedIndex
        {
            get
            {
                return pivotSelectedIndex;
            }
            set
            {
                pivotSelectedIndex = value;
                RaisePropertyChanged("PivotSelectedIndex");
                ExecuteOnUIThread(() =>
                {
                    PerformGetItems();
                });

            }
        }



        private ObservableCollection<SNSStatusViewModel> commentstome = new ObservableCollection<SNSStatusViewModel>();

        public ObservableCollection<SNSStatusViewModel> CommentsToMe
        {
            get { return commentstome; }
            set
            {
                commentstome = value;
                RaisePropertyChanged(() => CommentsToMe);
            }
        }

        private ObservableCollection<SNSStatusViewModel> commentsbyme = new ObservableCollection<SNSStatusViewModel>();
        public ObservableCollection<SNSStatusViewModel> CommentsByMe
        {
            get { return commentsbyme; }
            set
            {
                commentsbyme = value;
                RaisePropertyChanged(() => CommentsByMe);
            }
        }

        ObservableCollection<SNSStatusViewModel> mentions = new ObservableCollection<SNSStatusViewModel>();

        public ObservableCollection<SNSStatusViewModel> Mentions
        {
            get { return mentions; }
            set
            {
                mentions = value;
                RaisePropertyChanged(() => Mentions);
            }
        }

        ObservableCollection<SNSStatusViewModel> searchRsults = new ObservableCollection<SNSStatusViewModel>();

        public ObservableCollection<SNSStatusViewModel> SearchRsults
        {
            get { return searchRsults; }
            set
            {
                searchRsults = value;
                RaisePropertyChanged(() => SearchRsults);
            }
        }

        private SNSStatusViewModel selectedItem;

        public SNSStatusViewModel SelectedItem
        {
            get { return selectedItem; }
            set
            {
                selectedItem = value;
                RaisePropertyChanged(() => SelectedItem);
            }
        }

        public ObservableCollection<SNSProvider> SupportedProviders
        {
            get
            {
                var providers = SNSProviderManager.Current.GetAllSupportedProviders().ToObservableCollection();
                //if (providers.Count > 0)
                //    SelectedProvider = providers.Where((sp)=>sp.Type== SNSProviderType.Sina).FirstOrDefault();
                return providers;
            }
        }

        private SNSProvider selectedProvider;

        public SNSProvider SelectedProvider
        {
            get
            {
                return selectedProvider;
            }
            set
            {
                selectedProvider = value;
                RaisePropertyChanged(() => SelectedProvider);
            }
        }
        #endregion

        #region Command

        public DelegateCommand Authorize { get; set; }
        public DelegateCommand Search { get; set; }
        public DelegateCommand ChoosePhoto { get; set; }
        public DelegateCommand ClearPhoto { get; set; }
        public DelegateCommand Send { get; set; }
        public DelegateCommand ClearSearch { get; set; }

        #endregion

        public MainViewModel()
        {
            Messenger.Default.Register<WeiboTagClickEvent>(this, (e) =>
            {
                if (e.TargetUri.IsAbsoluteUri)
                {
                    var task = new WebBrowserTask();
                    task.Uri = e.TargetUri;
                    task.Show();
                }
            });

            CheckNetworkConnectivity();
            _ev = PhoneApplicationController.Current.Container.Resolve<IEventAggregator>();
            HasBindedAccount = AccountManager.Current.GetAllAccount().Any(a => a.IsBind == true);

            if (HasBindedAccount)
            {
                var user = AccountManager.Current.GetAllAccount().First();
                if (user.UserLite != null)
                    UserName = user.UserLite.Name;
            }
            //if (HasBindedAccount && AccountManager.Current.Count(a => a.IsActive) > 0)
            //{
            //    pagecount = (int)Math.Round((double)(PhoneApplicationController.Current.AppSetting.PageCount / AccountManager.Current.Count(a => a.IsActive)), 0);
            //    BindedAccounts = AccountManager.Current.GetAllAccount().Where((a) => { return a.IsBind == true; }).ToObservableCollection();

            //    _pollingSvc = PhoneApplicationController.Current.Container.Resolve<ISNSPollingService>();
            //    _pollingSvc.OnPollingStarted += new EventHandler<EventArgs>(_pollingSvc_OnPollingStarted);
            //    _pollingSvc.OnPollingCompleted += new EventHandler<SNSPollingEventArgs>(_pollingSvc_OnPollingCompleted);
            //    _pollingSvc.Start();
            //}

            PhoneApplicationController.Current.AppSetting.PropertyChanged += new PropertyChangedEventHandler(AppSetting_PropertyChanged);

            Authorize = new DelegateCommand(AuthorizeMethod, () => { return !Loading; });

            PropertyChanged += new PropertyChangedEventHandler(MainViewModel_PropertyChanged);


            Search = new DelegateCommand(SearchMethod, () => { return !Loading && !string.IsNullOrEmpty(searchKeyword); });

            ClearPhoto = new DelegateCommand(ClearPhotoMethod, () => { return !Loading && ImageToSend != null; });

            //ChoosePhoto = new DelegateCommand(ChoosePhotoMethod, () => { return !Loading; });

            Send = new DelegateCommand(SendMethod, () => { return !Loading; });
            //LoadFromStorage();
            ClearSearch = new DelegateCommand(() => { }, () => { return !Loading; });
            //Loading = true;
            //if (initStr.StartsWith("Search"))
            //{ 
            //    var q = initStr.Split('=');
            //    if (q.Length == 2)
            //    {
            //        SearchKeyword = q[1];
            //        Search.Execute();
            //        PivotSelectedIndex = 4;
            //    }
            //}
            //else if (!IsCachedDataLoad)
            //    LoadData();
            //else
            //    RefreshData();

            //FOR TEST 
            //ImageToSend = new BitmapImage(new Uri("/Images/Backgrounds5.jpg", UriKind.Relative));
        }

        void _pollingSvc_OnPollingStarted(object sender, EventArgs e)
        {
            lock (_countsObj)
            {
                _counts = new SNSCounts();
            }
        }

        void _pollingSvc_OnPollingCompleted(object sender, SNSPollingEventArgs e)
        {
            if (e.Counts != null)
            {
                lock (_countsObj)
                {
                    if (_counts == null)
                        _counts = e.Counts;
                    else
                    {
                        _counts = new SNSCounts()
                        {
                            Status = _counts.Status + e.Counts.Status,
                            Mentions = _counts.Mentions + e.Counts.Mentions,
                            Comments = _counts.Comments + e.Counts.Comments,
                        };
                    }
                }

                ExecuteOnUIThread(() =>
                {
                    if ((_counts.Status + _counts.Mentions + _counts.Comments) > 0)
                        CountInfoText = string.Format(AppResx.CountInfoTextTemplate, _counts.Status, _counts.Mentions, _counts.Comments);
                });
            }
            //throw new NotImplementedException();
        }

        void MainViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "Loading")
            {
                Authorize.RaiseCanExecuteChanged();
            }
        }

        void AppSetting_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "PageCount" && HasBindedAccount)
            {
                pagecount = (int)Math.Round((double)(PhoneApplicationController.Current.AppSetting.PageCount / AccountManager.Current.Count(a => a.IsActive)), 0);
            }
        }

        private void CheckNetworkConnectivity()
        {
            Timer t = new Timer((status) =>
            {
                var isAva = NetworkInterface.GetIsNetworkAvailable();

                ExecuteOnUIThread(
                    () =>
                    {
                        IsNetworkAvailable = isAva;

                        if (!IsNetworkAvailable)
                            MessageBox.Show(AppResx.NoConnection);
                    });
            }, null, 0, 6000);

        }

        /// <summary>
        /// Creates and adds a few ItemViewModel objects into the Items collection.
        /// </summary>
        protected override void LoadData()
        {
            if (!HasBindedAccount || Items.Count > 0)
            {
                return;
            }

            _statusSvc = PhoneApplicationController.Current.Container.Resolve<IStatusService>();

            if (!_statusSvc.IsActive)
            {
                MessageBox.Show(AppResx.NoBindedAccount);
                return;
            }

            //HasBindedAccount = true;

            var request = new SNSRequest() { Type = SNSType.HomeStatus };
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.COUNT, pagecount + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_FLAG, "0"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE, "0"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_TIME, "0"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.REQ_NUM, pagecount + ""));
            _statusSvc.GetTimeline(request, (data, result) =>
            {
                if (!result.IsSuccess)
                {
                    ExecuteOnUIThread(() => { MessageBox.Show(result.Message); });
                }
                else
                {
                    ResetCounts(request);
                    PopupItems<SNSStatusViewModel, SNSStatus>(Items, data, false, () =>
                    {
                        if (OnNextPagePerformed != null)
                            OnNextPagePerformed(Items.FirstOrDefault(), "home");

                        if (data != null && data.Count > 0 && data[0].Provider == SNSProviderType.Sina)
                        {
                            ThreadPool.QueueUserWorkItem((o) =>
                            {
                                UpdateSinaCounts(data);
                            });
                        }
                        //var sinaStatus = Items.FirstOrDefault(item => item.Item.Provider == SNSProviderType.Sina);
                        //if (sinaStatus != null)
                        //{
                        //    _pollingSvc.SinceID = sinaStatus.Item.Id;
                        //    ResetCounts(request);
                        //}
                    });
                    _page++;
                }
            });


            //_statusSvc.GetCommentsTimeline(SNSCommentsTimelineType.ByMe, parameters, (data) => {
            //    foreach (var comment in data)
            //    {
            //        Debug.WriteLine("{0}: {1}", DateTime.Now.ToLongTimeString(), comment.Text);
            //    }
            //});
            Loading = true;
        }

        private void UpdateSinaCounts(IEnumerable<SNSStatus> status)
        {
            //var sinaStatuses = items.Where(i => i.Item.Provider == SNSProviderType.Sina && i.Item.CommentCount == 0 && i.Item.RepostCount == 0);

            if (status == null || status.Count() == 0)
            {
                return;
            }

            var sb = new StringBuilder();

            status.ToList().ForEach(i => sb.AppendFormat("{0},", i.Id));

            var ids = sb.ToString();
            var req = new SNSRequest() { Type = SNSType.QueryCounts };
            req.Parameters.Add(new SNSParameter(SNSParametersConstants.IDS, ids));

            _statusSvc.GetCounts(req, (d, r) =>
            {
                if (!r.IsSuccess)
                {
                    ExecuteOnUIThread(() =>
                                       {
                                           MessageBox.Show(r.Message);
                                       });
                    return;
                }


                foreach (var i in d)
                {
                    if ((i.Comments + i.Mentions) > 0)
                    {
                        ExecuteOnUIThread<SNSCounts>((count) =>
                        {
                            var items = status.FirstOrDefault(j => j.Id == count.StatusId);
                            if (items != null)
                            {
                                items.CommentCount = count.Comments;
                                items.RepostCount = count.Mentions;
                            }
                        }, i);
                    }
                }
            });
        }

        private bool isNetworkAvailable;

        public bool IsNetworkAvailable
        {
            get { return isNetworkAvailable; }
            set
            {
                if (IsNetworkAvailable != value)
                {
                    isNetworkAvailable = value;
                    RaisePropertyChanged(() => IsNetworkAvailable);
                }
            }
        }

        private bool hasBindedAccount;

        public bool HasBindedAccount
        {
            get
            {
                return hasBindedAccount;
            }
            set
            {
                hasBindedAccount = value;
                RaisePropertyChanged(() => HasBindedAccount);
            }
        }

        protected override void Initialize()
        {
            _statusSvc = PhoneApplicationController.Current.Container.Resolve<IStatusService>();
        }

        private void SearchMethod()
        {
            if (string.IsNullOrEmpty(SearchKeyword))
            {

                return;
            }


            Loading = true;
            var request = new SNSRequest() { Type = SNSType.SearchStatus };
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_FLAG, "1"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.REQ_NUM, pagecount + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_INFO, ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.TREND_NAME, SearchKeyword));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.KEYWORD, SearchKeyword));

            SearchRsults.Clear();
            _pagingInfo = null;
            _statusSvc.GetTimeline(
            request, (data, result) =>
            {
                if (!result.IsSuccess)
                {
                    ExecuteOnUIThread(() => { MessageBox.Show(result.Message); Loading = false; });
                    return;
                }
                if (result.PagingInfo != null)
                {
                    _pagingInfo = result.PagingInfo;
                }
                PopupItems<SNSStatusViewModel, SNSStatus>(SearchRsults, data, true, () =>
                {
                    if (OnNextPagePerformed != null)
                        OnNextPagePerformed(SearchRsults.FirstOrDefault(), "search");
                });
            });
        }

        private void AuthorizeMethod()
        {
            Loading = true;
            Authorize.RaiseCanExecuteChanged();

            SNSProviderType t = SNSProviderType.RenRen;
            //if (SelectedProvider == null || SelectedProvider.Type == SNSProviderType.Unknow)
            //{
            //    t = SNSProviderType.Sina;
            //}
            //else
            //{
            //    t = SelectedProvider.Type;
            //}

            AuthorizeHelper.NewRequestToken(t, (account, result) =>
            {
                ExecuteOnUIThread(() =>
                       {
                           if (!result.IsSuccess)
                               MessageBox.Show(result.Message);
                           else
                           {
                               Loading = false;
                               PhoneApplicationController.Current.Container.Resolve<IEventAggregator>().GetEvent<NavigationRequestEvent>().Publish(new NavigationContext() { Destination = new Uri("/Views/AuthPage.xaml", UriKind.RelativeOrAbsolute), SimpleParameter = account.AccountID });
                           }
                       });
            });
        }

        private void PerformGetItems()
        {
            switch (PivotSelectedIndex)
            {
                case 0:
                    LoadData();
                    break;
                //case 1:
                //    GetMentions();
                //    break;
                //case 2:
                //    GetCommentsToMe();
                //    break;
                //case 3:
                //    GetCommentsByMe();
                //    break;
                default:
                    break;
            }
        }

        private void GetMentions()
        {
            if (!HasBindedAccount || Mentions.Count > 0)
                return;
            SNSRequest request = new SNSRequest() { Type = SNSType.MentionsStatus };
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.COUNT, pagecount + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_FLAG, "0"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.REQ_NUM, pagecount + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_TIME, "0"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.TYPE, (0x1 | 0x2 | 0x8 | 0x10 | 0x20) + ""));

            _statusSvc.GetTimeline(request, (data, result) =>
            {
                if (!result.IsSuccess)
                {
                    ExecuteOnUIThread(() => { MessageBox.Show(result.Message); Loading = false; });
                    return;
                }
                else
                {
                    ResetCounts(request);
                    var sinaStatus = Mentions.FirstOrDefault(item => item.Item.Provider == SNSProviderType.Sina);
                    if (sinaStatus != null)
                    {
                        _pollingSvc.SinceID = sinaStatus.Item.Id;
                    }
                    PopupItems<SNSStatusViewModel, SNSStatus>(Mentions, data, false, () =>
                    {
                        if (OnNextPagePerformed != null)
                            OnNextPagePerformed(Mentions.FirstOrDefault(), "mentions");
                        if (data != null && data.Count > 0 && data[0].Provider == SNSProviderType.Sina)
                        {
                            ThreadPool.QueueUserWorkItem((o) =>
                            {
                                UpdateSinaCounts(data);
                            });
                        }
                    });
                }

            });
            Loading = true;
        }

        private void GetCommentsByMe()
        {
            if (!HasBindedAccount || CommentsByMe.Count > 0)
                return;
            SNSRequest request = new SNSRequest() { Type = SNSType.CommentsByMe };
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.COUNT, pagecount + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_FLAG, "0"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.REQ_NUM, pagecount + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_TIME, "0"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.TYPE, 0x40 + ""));
            _statusSvc.GetTimeline(request, (data, result) =>
            {
                PopupItems<SNSStatusViewModel, SNSStatus>(CommentsByMe, data, false, () =>
                {
                    if (OnNextPagePerformed != null)
                        OnNextPagePerformed(CommentsByMe.FirstOrDefault(), "commentbyme");
                });

            });
            Loading = true;
        }

        private void GetCommentsToMe()
        {
            if (!HasBindedAccount || CommentsToMe.Count > 0)
                return;
            SNSRequest request = new SNSRequest() { Type = SNSType.CommentsToMe };
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.COUNT, pagecount + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_FLAG, "0"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.REQ_NUM, pagecount + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_TIME, "0"));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.TYPE, 0x40 + ""));

            _statusSvc.GetTimeline(request, (data, result) =>
            {
                if (!result.IsSuccess)
                {
                    ExecuteOnUIThread(() => { MessageBox.Show(result.Message); Loading = false; });
                    return;
                }
                else
                {
                    ResetCounts(request);
                    var sinaStatus = CommentsToMe.FirstOrDefault(item => item.Item.Provider == SNSProviderType.Sina);
                    if (sinaStatus != null)
                    {
                        _pollingSvc.SinceID = sinaStatus.Item.Id;
                    }
                    PopupItems<SNSStatusViewModel, SNSStatus>(CommentsToMe, data, false, () =>
                    {
                        if (OnNextPagePerformed != null)
                            OnNextPagePerformed(CommentsToMe.FirstOrDefault(), "commenttome");
                    });
                }
            });
            Loading = true;
        }

        private void ClearPhotoMethod()
        {
            ImageToSend = null;
        }

        private void SendMethod()
        {
            if (string.IsNullOrEmpty(StatusToUpdate))
                return;
            //var text = Helper.GetUrlEncodeStr(StatusToUpdate);
            Loading = true;
            SNSRequest request;
            if (ImageToSend == null)
            {
                request = new SNSRequest() { Type = SNSType.AddStatus, WebMethod = Hammock.Web.WebMethod.Post };
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.STATUS_TEXT, StatusToUpdate));
            }
            else
            {
                byte[] data;
                using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (file.FileExists("testfile.jpeg"))
                        file.DeleteFile("testfile.jpeg");

                    using (IsolatedStorageFileStream fileStream = file.OpenFile("testfile.jpeg", FileMode.OpenOrCreate, FileAccess.ReadWrite))
                    {
                        // Get an Image Stream
                        using (MemoryStream ms = new MemoryStream())
                        {
                            WriteableBitmap btmMap = new WriteableBitmap(ImageToSend);

                            // write an image into the stream
                            Extensions.SaveJpeg(btmMap, ms,
                                ImageToSend.PixelWidth, ImageToSend.PixelHeight, 0, AppSetting.UploadImageResolution.Quality);

                            // reset the stream pointer to the beginning
                            ms.Seek(0, 0);
                            //read the stream into a byte array
                            data = new byte[ms.Length];
                            ms.Read(data, 0, data.Length);
                        }
                        fileStream.Write(data, 0, data.Length);
                        fileStream.Close();
                    }
                }

                request = new SNSRequest() { Type = SNSType.Upload, WebMethod = Hammock.Web.WebMethod.Post };

                //FOR TENCENT
                request.Parameters.Add(new SNSFileParameter(SNSParametersConstants.PIC, "testfile.jpeg", data) { Style = ParameterStyle.FilePath });

                //FOR RENREN
                request.Parameters.Add(new SNSFileParameter(SNSParametersConstants.UPLOAD, "testfile.jpeg", data) { Style = ParameterStyle.FilePath });
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.CAPTION, StatusToUpdate) { Style = ParameterStyle.Post });

                request.Parameters.Add(new SNSParameter(SNSParametersConstants.STATUS_TEXT, Uri.EscapeDataString(StatusToUpdate)) { Style = ParameterStyle.Post });

            }

            request.Parameters.Add(new SNSParameter(SNSParametersConstants.CONTENT, StatusToUpdate));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.CLIENT_IP, "127.0.0.1"));



            _statusSvc.UpdateStatus(request, (data, result) =>
            {
                ExecuteOnUIThread(() =>
                {
                    if (!result.IsSuccess)
                    {
                        ExecuteOnUIThread(() => { MessageBox.Show(result.Message); Loading = false; });

                        return;
                    }
                    else
                    {
                        //PopupItems(Items, new List<SNSStatus>() { data }, true);
                        //Debug.WriteLine("{0}: {1}", DateTime.Now.ToLongTimeString(), data.Text);
                        PivotSelectedIndex = 0;
                        RefreshTimeLine("home");
                        //if (ImageToSend != null)
                        //    ImageToSend = null;
                    }

                    Loading = false;
                    ClearStatusToSend();
                });

            });
        }

        private void ClearStatusToSend()
        {
            StatusToUpdate = string.Empty;
            ImageToSend = null;
            //throw new NotImplementedException();
        }

        internal void NextPage(string p)
        {
            SNSRequest request = null;
            string pageflag = "1";
            long pagetime = 0;
            long maxid = 0;
            bool getCounts = false;
            ObservableCollection<SNSStatusViewModel> items = null;
            switch (p)
            {
                case "home":
                    items = Items;
                    request = new SNSRequest() { Type = SNSType.HomeStatus };
                    getCounts = true;
                    break;
                case "mentions":
                    items = Mentions;
                    getCounts = true;
                    request = new SNSRequest() { Type = SNSType.MentionsStatus };
                    request.Parameters.Add(new SNSParameter(SNSParametersConstants.TYPE, (0x1 | 0x2 | 0x8 | 0x10 | 0x20) + ""));
                    break;
                case "commenttome":
                    items = CommentsToMe;
                    request = new SNSRequest() { Type = SNSType.CommentsToMe };
                    request.Parameters.Add(new SNSParameter(SNSParametersConstants.TYPE, 0x40 + ""));
                    break;
                case "commentbyme":
                    items = CommentsByMe;
                    request = new SNSRequest() { Type = SNSType.CommentsByMe };
                    request.Parameters.Add(new SNSParameter(SNSParametersConstants.TYPE, 0x40 + ""));
                    break;
                case "search":
                    if (string.IsNullOrEmpty(SearchKeyword))
                    {
                        return;
                    }
                    getCounts = true;
                    items = SearchRsults;
                    request = new SNSRequest() { Type = SNSType.SearchStatus };
                    request.Parameters.Add(new SNSParameter(SNSParametersConstants.TREND_NAME, SearchKeyword));
                    request.Parameters.Add(new SNSParameter(SNSParametersConstants.KEYWORD, SearchKeyword));
                    if (_pagingInfo != null)
                        request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_INFO, _pagingInfo.PageInfo));
                    break;
                default:
                    break;
            }

            if (items.Count == 0 || request == null)
                return;

            GetPagingInfo(items, ref pagetime, ref maxid, false);

            request.Parameters.Add(new SNSParameter(SNSParametersConstants.COUNT, pagecount + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE, _page + ""));
            if (maxid != 0)
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.MAX_ID, maxid + ""));
            if (p != "search")
                request.Parameters.Insert(0, new SNSParameter(SNSParametersConstants.PAGE_TIME, pagetime + ""));
            request.Parameters.Insert(0, new SNSParameter(SNSParametersConstants.REQ_NUM, pagecount + ""));
            request.Parameters.Insert(0, new SNSParameter(SNSParametersConstants.PAGE_FLAG, pageflag));

            _statusSvc.GetTimeline(request, (data, result) =>
           {
               if (!result.IsSuccess)
               {
                   ExecuteOnUIThread(() => { MessageBox.Show(result.Message); Loading = false; });
                   return;
               }
               if (result.PagingInfo != null)
               {
                   _pagingInfo = result.PagingInfo;
               }

               //int index = 0;
               //if (items.Count > 0 && data != null)
               //{
               //    index = items.Count;
               //}

               PopupItems<SNSStatusViewModel, SNSStatus>(items, data, false, () =>
               {
                   if (p == "home")
                       _page++;
                   //if (OnNextPagePerformed != null)
                   //    OnNextPagePerformed(items[index], p);
                   if (getCounts && data != null && data.Count > 0 && data[0].Provider == SNSProviderType.Sina)
                   {
                       ThreadPool.QueueUserWorkItem((o) =>
                       {
                           UpdateSinaCounts(data);
                       });
                   }
               });
           });

            Loading = true;
        }

        public static void GetPagingInfo(IEnumerable<SNSStatusViewModel> items, ref long pagetime, ref long id, bool isRefresh)
        {
            if (isRefresh)
            {
                var firstItemTencent = items.FirstOrDefault(item => item.Item.Account.ServiceProvider == SNSProviderType.Tencent);
                if (firstItemTencent != null)
                {
                    pagetime = firstItemTencent.Item.Timestamp;
                }

                //for sina

                var firstItemSina = items.FirstOrDefault(item => item.Item.Account.ServiceProvider == SNSProviderType.Sina);
                if (firstItemSina != null)
                {
                    id = firstItemSina.Item.Id + 1;
                }
            }
            else
            {
                var firstItemTencent = items.LastOrDefault(item => item.Item.Account.ServiceProvider == SNSProviderType.Tencent);
                if (firstItemTencent != null)
                {
                    pagetime = firstItemTencent.Item.Timestamp;
                }

                //for sina

                var firstItemSina = items.LastOrDefault(item => item.Item.Account.ServiceProvider == SNSProviderType.Sina);
                if (firstItemSina != null)
                {
                    id = firstItemSina.Item.Id - 1;
                }
            }
        }

        internal void RefreshTimeLine(string p)
        {
            SNSRequest request = null;
            string pageflag = "2";
            long pagetime = 0;
            long sinceid = 0;
            bool getCounts = false;
            ObservableCollection<SNSStatusViewModel> items = null;
            switch (p)
            {
                case "home":
                    items = Items;
                    request = new SNSRequest() { Type = SNSType.HomeStatus };
                    getCounts = true;
                    break;
                case "mentions":
                    items = Mentions;
                    request = new SNSRequest() { Type = SNSType.MentionsStatus };
                    request.Parameters.Add(new SNSParameter(SNSParametersConstants.TYPE, (0x1 | 0x2 | 0x8 | 0x10 | 0x20) + ""));
                    getCounts = true;
                    break;
                case "commenttome":
                    items = CommentsToMe;
                    request = new SNSRequest() { Type = SNSType.CommentsToMe };
                    request.Parameters.Add(new SNSParameter(SNSParametersConstants.TYPE, 0x40 + ""));
                    break;
                case "commentbyme":
                    items = CommentsByMe;
                    request = new SNSRequest() { Type = SNSType.CommentsByMe };
                    request.Parameters.Add(new SNSParameter(SNSParametersConstants.TYPE, 0x40 + ""));
                    break;
                case "search":
                    items = SearchRsults;
                    getCounts = true;
                    request = new SNSRequest() { Type = SNSType.SearchStatus };
                    break;
                default:
                    break;
            }

            if (request == null)
                return;

            GetPagingInfo(items, ref pagetime, ref sinceid, true);

            request.Parameters.Add(new SNSParameter(SNSParametersConstants.COUNT, pagecount + ""));
            if (sinceid != 0)
                request.Parameters.Add(new SNSParameter(SNSParametersConstants.SINCE_ID, sinceid + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_FLAG, pageflag));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.PAGE_TIME, pagetime + ""));
            request.Parameters.Add(new SNSParameter(SNSParametersConstants.REQ_NUM, pagecount + ""));

            _statusSvc.GetTimeline(request, (data, result) =>
            {
                if (!result.IsSuccess)
                {
                    ExecuteOnUIThread(() => { MessageBox.Show(result.Message); Loading = false; });
                    return;
                }
                else
                {
                    ResetCounts(request);
                    var sinaStatus = Items.FirstOrDefault(item => item.Item.Provider == SNSProviderType.Sina);
                    if (sinaStatus != null)
                    {
                        _pollingSvc.SinceID = sinaStatus.Item.Id;
                    }
                }
                PopupItems<SNSStatusViewModel, SNSStatus>(items, data, true, () =>
                {
                    if (OnRefreshed != null)
                        OnRefreshed(items.FirstOrDefault(), p);
                    if (getCounts && data != null && data.Count > 0 && data[0].Provider == SNSProviderType.Sina)
                    {
                        ThreadPool.QueueUserWorkItem((o) =>
                        {
                            UpdateSinaCounts(data);
                        });
                    }
                });
            });

            Loading = true;
        }

        private void ResetCounts(SNSRequest request)
        {
            if (_counts == null)
                return;
            string type = "0";
            //long since_id = 0;
            switch (request.Type)
            {
                case SNSType.HomeStatus:
                    type = "5";
                    _counts.Status = 0;

                    break;
                case SNSType.MentionsStatus:
                    type = "2";
                    _counts.Mentions = 0;
                    break;
                case SNSType.CommentsToMe:
                    type = "1";
                    _counts.Comments = 0;
                    break;
                default:
                    break;
            }

            SNSRequest req = new SNSRequest() { Type = SNSType.ResetCount };
            req.Parameters.Add(new SNSParameter(SNSParametersConstants.OP, "1"));
            req.Parameters.Add(new SNSParameter(SNSParametersConstants.TYPE, type));

            _statusSvc.ResetCounts(req, (c, r) =>
            {
                if (!r.IsSuccess)
                {
                    ExecuteOnUIThread(() => { MessageBox.Show(r.Message); Loading = false; });
                    return;
                }
                else
                {
                    ExecuteOnUIThread(() =>
                    {
                        //if ((_counts.Status + _counts.Mentions + _counts.Comments) > 0)
                        if (!string.IsNullOrEmpty(CountInfoText))
                            CountInfoText = string.Format(AppResx.CountInfoTextTemplate, _counts.Status, _counts.Mentions, _counts.Comments);
                    });
                }
            });
            //throw new NotImplementedException();
        }

        bool showQuickSetting;

        public bool ShowQuickSetting
        {
            get { return showQuickSetting; }
            set
            {
                showQuickSetting = value;
                RaisePropertyChanged(() => ShowQuickSetting);
            }
        }

        internal void Init()
        {
            LoadData();
        }
    }
}
